package com.school.admin.common.filter;

import cn.hutool.json.JSONUtil;
import com.school.admin.common.annotation.ReturnValueEncryption;
import com.school.admin.common.utils.RsaUtils;
import com.school.admin.common.utils.UserInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author ：zzz
 * @date ：Created in 2021/3/28 22:09
 * @description：跨域
 * @modified By：
 * @version: $
 */
@RestControllerAdvice
public class ResponseBodyAdviceFilter implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(ReturnValueEncryption.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        String s = JSONUtil.toJsonStr(body);
        RsaUtils.encryption(s);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        //返回
        stringStringHashMap.put("sign", UserInfoUtil.getSign());
        stringStringHashMap.put("postData", RsaUtils.encryption(s));
        return stringStringHashMap;
    }
}
